# -*- coding: utf-8 -*-
"""
Created on Fri Aug  2 16:35:39 2024

@author: xiaobojie
"""
#%%提取pdf页面,使用list过滤
import PyPDF2

def extract_pages_to_files(pdf_list, pages_to_extract):
    for pdf in pdf_list:
        with open(pdf, 'rb') as file:
            pdf_reader = PyPDF2.PdfReader(file)
            for page_number in pages_to_extract:
                if page_number < len(pdf_reader.pages):
                    pdf_writer = PyPDF2.PdfWriter()
                    pdf_writer.add_page(pdf_reader.pages[page_number])
                    
                    output_filename = f'{pdf}_page_{page_number + 1}.pdf'
                    with open(output_filename, 'wb') as out_file:
                        pdf_writer.write(out_file)
                    print(f'Extracted page {page_number + 1} from {pdf} to {output_filename}')

# 示例 PDF 文件列表和要提取的页面
pdf_files = ['file1.pdf', 'file2.pdf']
pages = [0, 1]  # 提取每个 PDF 的第一页和第二页（索引从0开始）

extract_pages_to_files(pdf_files, pages)



#%%合并list中的pdf,文件可用list过滤

import PyPDF2
import os

def merge_pdfs(pdf_list, output_filename):
    pdf_writer = PyPDF2.PdfWriter()

    for pdf in pdf_list:
        with open(pdf, 'rb') as file:
            pdf_reader = PyPDF2.PdfReader(file)
            for page in range(len(pdf_reader.pages)):
                pdf_writer.add_page(pdf_reader.pages[page])

    with open(output_filename, 'wb') as out_file:
        pdf_writer.write(out_file)

# 获取当前目录中的 PDF 文件列表
pdf_files = [f for f in os.listdir() if f.endswith('.pdf')]
output_pdf = 'merged.pdf'

merge_pdfs(pdf_files, output_pdf)







#%%合并文件夹内的pdf

'''
合并pdf
函数封装
优先使用
'''

import PyPDF2 as pp
import os
import re

def merge_pdfs(input_directory, output_file):
    """
    合并指定目录下的所有PDF文件，并将合并后的PDF保存到指定的输出文件中。

    参数:
    input_directory (str): 包含要合并的PDF文件的目录。
    output_file (str): 合并后的PDF文件的输出路径。
    """
    try:
        # 切换到指定目录
        os.chdir(input_directory)
        
        # 列出文件夹内所有pdf并排序
        pdf_files = [f for f in os.listdir('.') if re.match(r'.*\.pdf$', f)]
        pdf_files.sort(key=str.lower)  # 将文件按字母顺序排序

        # 创建一个PdfWriter对象
        pdf_writer = pp.PdfWriter()

        # 将所有pdf文件添加到pdf_writer
        for pdf_file in pdf_files:
            with open(pdf_file, 'rb') as pdf_obj:
                pdf_reader = pp.PdfReader(pdf_obj)
                pdf_writer.append(pdf_reader)  # 使用 append 方法将整个文档添加

        # 将pdf_writer写入文件
        with open(output_file, 'wb') as pdf_out:
            pdf_writer.write(pdf_out)

        print(f"PDF文件已成功合并并保存到: {output_file}")

    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    #path = 'Z:/virtual_share/合并pdf'
    path = '/Users/earlshaw/Downloads/salary'
    output_pdf = 'pro.pdf'
    
    merge_pdfs(path, output_pdf)
    
#%%

'''
合并pdf
无封装
仅学习
'''


import PyPDF2 as pp
import os, re


path = 'Z:/virtual_share/合并pdf'



os.chdir(path)
# print(os.getcwd())


# 列出文件夹内所有pdf并排序
a_files = []
for f in os.listdir('.'):
    if re.match(r'.*pdf', f):
        a_files.append(f)
a_files.sort(key=str.lower) #将文件按字母顺序排序
# print(pdf_files)

# 将所有pdf页面写入pdf_wr
pdf_wr = pp.PdfWriter()
# print(pdf_wr)
# print(pdf_files)
for f2 in a_files:
    pdf_obj = open(f2, 'rb')
    pdf_r = pp.PdfReader(pdf_obj)
    for page_num in range(len(pdf_r.pages)): 
        page_obj = pdf_r.pages[page_num]
        pdf_wr.add_page(page_obj)  #合并时只能按页，能否将整个文档添加？
    pdf_obj.close()

# 将pdf_wr写入文件
pdf_out = open('pro.pdf', 'wb')
pdf_wr.write(pdf_out)
pdf_out.close()

#%%旋转90度

from PyPDF2 import PdfReader, PdfWriter



# path = '/Users/earlshaw/Desktop/pdfa/证据4--加班考勤记录.pdf'

def rotate_pdf_pages(input_pdf, output_pdf):
    # 读取现有的 PDF
    reader = PdfReader(input_pdf)
    writer = PdfWriter()

    # 遍历每一页并旋转
    for page in reader.pages:
        page.rotate(90)  # 旋转 90 度
        writer.add_page(page)

    # 将结果写入新的 PDF 文件
    with open(output_pdf, "wb") as output_stream:
        writer.write(output_stream)

# 使用示例
rotate_pdf_pages('证据7--收入纳税明细查询.pdf', "output_rotated7.pdf")

#%%右上加页码

from PyPDF2 import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.colors import black
import io

def add_page_numbers(input_pdf, output_pdf, start_page=17):
    reader = PdfReader(input_pdf)
    writer = PdfWriter()

    for i, page in enumerate(reader.pages):
        if i + 1 >= start_page:
            packet = io.BytesIO()
            can = canvas.Canvas(packet, pagesize=letter)
            
            # 设置字体、大小和颜色
            can.setFont("Helvetica", 12)
            can.setFillColor(black)
            
            # 调整页码的位置
            can.drawString(500, 780, f"Page {i + 1}")
            can.save()

            packet.seek(0)
            new_pdf = PdfReader(packet)
            page.merge_page(new_pdf.pages[0])
        
        writer.add_page(page)

    with open(output_pdf, "wb") as output_stream:
        writer.write(output_stream)

# 使用示例
add_page_numbers("output_rotated.pdf", "output_with_page_numbers.pdf", start_page=17)

